package com.locationtracker.plus.ui.activity

import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresPermission
import androidx.navigation.Navigation
import com.blankj.utilcode.util.ToastUtils
import com.google.android.gms.ads.AdRequest
import com.gyf.immersionbar.ktx.immersionBar
import com.locationtracker.plus.R
import com.locationtracker.plus.app.base.BaseActivity
import com.locationtracker.plus.app.eventViewModel
import com.locationtracker.plus.app.util.LocationForegroundService
import com.locationtracker.plus.databinding.ActivityMainBinding
import com.locationtracker.plus.ui.fragment.home.HomeFragment
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel

class MainActivity : BaseActivity<BaseViewModel, ActivityMainBinding>() {

    private var exitTime = 0L

    private var registerForActivityResult: ActivityResultLauncher<Intent>? = null

    @RequiresPermission("android.permission.INTERNET")
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            fitsSystemWindows(true)
            statusBarDarkFont(true)
        }
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val nav = Navigation.findNavController(this@MainActivity, R.id.host_fragment)
                if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.navigation_home) {
                    //如果当前界面不是主页，那么直接调用返回即可
                    nav.navigateUp()
                } else {
                    //是主页
                    if (System.currentTimeMillis() - exitTime > 2000) {
                        ToastUtils.showShort("Press back again to exit")
                        exitTime = System.currentTimeMillis()
                    } else {
                        finish()
                    }
                }
            }
        })

        //跳转逻辑
        jumpAction()

        registerForActivityResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(), activityResultRegistry
        ) { result ->
            val contactUri = result.data?.data
            contactUri?.let {
                contentResolver.query(contactUri, null, null, null, null).use { cursor ->
                    if (cursor?.moveToFirst() == true) {
                        var number = ""
                        var name = ""
                        val numberIndex =
                            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

                        if (numberIndex != -1) {
                            number = cursor.getString(numberIndex)
                            if (number.isNotEmpty()) {
                                eventViewModel.chooseContactResult.value = number.replace(" ", "")
                            }
                        }

                        val nameIndex =
                            cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                        if (nameIndex != -1) {
                            name = cursor.getString(nameIndex)
                        }
                        Log.e("TAG", "$name:$number")
                    }
                }
            }
        }
        LocationForegroundService.startService(this)
        mDatabind.adView.loadAd(AdRequest.Builder().build())
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        //跳转逻辑
        jumpAction()
    }

    override fun onResume() {
        super.onResume()
        mDatabind.adView.resume()
    }

    public override fun onPause() {
        mDatabind.adView.pause()
        super.onPause()
    }

    override fun onDestroy() {
        mDatabind.adView.destroy()
        LocationForegroundService.stopService(this)
        super.onDestroy()
    }

    override fun createObserver() {
        eventViewModel.jumpEvent.observeInActivity(this) {
            jumpAction()
        }
        eventViewModel.chooseContact.observeInActivity(this) {
            registerForActivityResult?.launch(
                Intent(
                    Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                )
            )
        }
    }

    private fun jumpAction() {
        eventViewModel.jumpEvent.value?.let {
            when (it.action) {
                else -> ToastUtils.showShort("UnSupport Action Type: ${it.action}，Pls Upgrade App!")
            }
            eventViewModel.jumpEvent.value = null
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == HomeFragment.REQUEST_CHECK_SETTINGS && resultCode == -1) {
            when (resultCode) {
                -1 -> eventViewModel.requestLocation.value = System.currentTimeMillis()
                0 -> ToastUtils.showShort("Location not enabled,user cancelled.")
            }

        }
    }
}